import type { ConsultOrderItem, FollowType } from '@/types/consult'
import { onMounted, onUnmounted, ref, type Ref } from 'vue'
import {
  CancelOrder,
  DeleteOrder,
  followDoctor,
  getPrescription
} from '@/services/consult'
import {
  showFailToast,
  showImagePreview,
  showSuccessToast,
  showToast,
  type FormInstance
} from 'vant'
import { OrderType } from '@/enums'
import { getMedicalOrderDetail } from '@/services/order'
import type { OrderDetail } from '@/types/order'
import { sendMobileCode } from '@/services/user'
import type { CodeType, User } from '@/types/user'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores'

const loading = ref(false)
export const useFollow = (type: FollowType = 'doc') => {
  // 给参数设定关注类型
  // 关注逻辑
  const follow = async (doc: { id: string; likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
      await followDoctor(doc.id, type) // 注意传入的是数据,而非对象,由自己设置api请求时决定
      doc.likeFlag = doc.likeFlag === 0 ? 1 : 0
    } finally {
      // 最终都会执行这代码
      loading.value = false
    }
  }
  return { loading, follow }
}

// 使用 查看处方方法
export const useShowPrescriptionPic = () => {
  const showPrescriptionPic = async (id?: string) => {
    if (id) {
      const res = await getPrescription(id)
      showImagePreview([res.data.url])
    }
  }
  return { showPrescriptionPic }
}

// 使用 取消订单方法
export const useCanelOreder = () => {
  // 取消订单 逻辑
  // 1.定义 取消订单api
  // 2.绑定点击事件,调用 api
  // 3.成功或失败 提示
  const loading = ref(false)
  const onCancelOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    await CancelOrder(item.id)
      .then(() => {
        // 修改订单状态
        item.status = OrderType.ConsultCancel
        item.statusValue = '已取消'
        showSuccessToast('已取消订单')
      })
      .catch(() => {
        showFailToast('取消失败')
      })
      .finally(() => {
        loading.value = false
      })
  }
  return { loading, onCancelOrder }
}

/**
 * 使用 删除订单方法
 * @param callback 回调函数(要处理的逻辑)
 */
export const useDeleteOrder = (callback: () => void) => {
  const loading = ref(false)
  const deleteConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    // 通过是否传入 '布尔值' 判断是否发送请求删除订单
    await DeleteOrder(item.id)
      .then(() => {
        // 设置回调函数,成功之后,立即执行
        callback && callback()
        showSuccessToast('删除成功')
      })
      .catch(() => {
        showFailToast('删除失败')
      })
      .finally(() => {
        loading.value = false
      })
  }
  return { loading, deleteConsultOrder }
}

/**
 * 使用 获取药品订单详情方法
 * @param id 药品订单id
 */
export const useOrderMedicalDetail = (id: string) => {
  const loading = ref(false)
  const order = ref<OrderDetail>()
  onMounted(async () => {
    try {
      loading.value = true
      const res = await getMedicalOrderDetail(id)
      order.value = res.data
    } finally {
      loading.value = false
    }
  })
  return { order, loading }
}

/**
 *  使用发送短信验证码-函数
 * @param mobile 手机号
 * @param codeType 发送短信类型
 * @param agree 是否勾选协议
 */
export const useMobileCode = (
  mobile: Ref<string>,
  codeType: CodeType,
  agree?: Ref<boolean>
) => {
  // 发送验证码,绑定手机
  // api接口函数
  // 发送验证码逻辑
  // 倒计时逻辑
  const form = ref<FormInstance | null>(null)
  const time = ref(0)
  const code = ref('')
  let timeId: number
  const send = async () => {
    // 勾选 协议
    if (agree?.value !== undefined) {
      if (!agree.value) return showToast('请勾选用户协议')
    }

    // 时间>0 不作任何操作
    if (time.value > 0) return
    // 校验 手机号码是否正确,再发 请求
    // validate需要传入name或name[]属性校验,返回promise,通过ref获取form表单方法
    await form.value?.validate('mobile').then(async () => {
      const res = await sendMobileCode(mobile.value, codeType)
      code.value = res.data.code
    })
    showToast('发送验证码成功')
    time.value = 60
    // 开始倒计时之前,确保没有定时器存在
    if (timeId) clearInterval(timeId)
    timeId = setInterval(() => {
      time.value--
      // 小于零,清除 定时器
      if (time.value <= 0) clearInterval(timeId)
    }, 1000)
  }
  onUnmounted(() => {
    clearInterval(timeId)
  })
  return { send, time, form, code }
}

// 使用登录成功后的操作-函数
export const useLoginSuccess = () => {
  // 登录成功后的处理: 1.保存用户信息 2.跳转到来源页面,不记录当前页面历史记录3.提示
  const router = useRouter()
  // const route = )
  const store = useUserStore()
  const loginSuccess = (res: { data: User }) => {
    store.setUser(res.data)
    router.replace(store.returnUrl || '/user')
  }
  return loginSuccess
}
